#include "csearchive.h"


CSeArchive::CSeArchive(uint32 a_buf_size)
{
    buf = new char[a_buf_size];
    memset(buf,0x00,a_buf_size);
    bufptr = buf;
    buf_saved = buf;
    buf_size = a_buf_size;
    data_size = 0;
    data_size_saved = 0;
    free_buf_on_exit = false;
    m_blSerializeOperationFailed = false;
}

CSeArchive::CSeArchive(const char *a_buf, uint32 a_buf_size, bool dup_buf)
{
    buf = new char[BUF_GROW_SIZE * 3];
    memcpy(buf,a_buf, a_buf_size);
    bufptr = buf;
    buf_saved = buf;
    buf_size = BUF_GROW_SIZE * 3;
    data_size = a_buf_size;
    data_size_saved = 0;
    free_buf_on_exit = false;
    m_blSerializeOperationFailed = false;

}

CSeArchive::~CSeArchive()
{
    if(sizeof(buf) != 0)
    {
        delete[] buf;
        buf = nullptr;
        bufptr = nullptr;
        buf_saved = nullptr;
    }
}

int CSeArchive::getStrlen(char *buf)
{
    if(buf == nullptr)
        return 0;
    int count = 0;
    //abcdef
    while(*buf != '\0' && buf != nullptr && count < data_size)
    {
        buf++;
        count++;
    }
    return count;

}

void CSeArchive::reset_buf()
{
    destoryMemory();
}

char *CSeArchive::get_buf(string &strData)
{
    strData = std::string(buf,data_size);
    return buf;
}

void CSeArchive::writeMemory(const char *ptr, int len)
{
    if(ptr == nullptr)
        return;
    memcpy(bufptr,ptr,len);
    data_size += len;
    bufptr += len;
}

void CSeArchive::getMemory(char *ptr, int len)
{
    if(len > data_size || ptr == nullptr)
        return;
    memcpy(ptr,bufptr,len);
}

void CSeArchive::destoryMemory()
{
    if(sizeof(buf) != 0)
    {
        delete[] buf;
        buf = nullptr;
        bufptr = nullptr;
        buf_saved = nullptr;
    }
}

void CSeArchive::bufPtrMove(int size)
{
    bufptr += size;
}

uint32 CSeArchive::get_buf_used()
{
    return data_size;
}


